package com.lry.basic.thread.demo;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Storage {

    private final int MAX_SIZE = 10;
    public static int pro = 0;
    public static int cos = 0;

    private LinkedList<Object> list = new LinkedList();

    public void produce(){
        while(pro<48){

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (list){

                while(list.size()+1>MAX_SIZE){
                    try {
                        //释放锁
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                list.add(new Object());
                pro++;
                System.out.println("生产者"+Thread.currentThread().getName()+"存入了产品"+pro);
                list.notifyAll();//通知其他线程

                //synchronized代码块执行完毕，也会释放锁
            }

        }
    }

    public void consume()  {
        while(cos<48) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (list) {
                while (list.size() == 0) {
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                list.remove();
                cos++;
                System.out.println("消费者" + Thread.currentThread().getName() + "消费了产品" + cos);
                list.notifyAll();
            }
        }
    }


}
